package com.example.dao.impl;

import com.example.common.R;
import com.example.dao.CommentDao;
import com.example.pojo.entity.ApComment;
import com.example.pojo.req.CommentReq;
import com.example.pojo.vo.CommentVo;
import com.example.pojo.vo.LoginVo;
import com.example.utils.JDBCUtil;
import com.example.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class CommentDaoImpl implements CommentDao {

    /**
     * 发布评论
     *
     * @param comment
     * @return
     */
    @Override
    public R addComment(CommentReq comment, String token) throws Exception {
        Connection connection = JDBCUtil.connection();
        String sql1 = null;
        PreparedStatement ps1 = null;
        String name = null;
        //回复功能,获取用户名称
        String replyComment = null;
        if (StringUtils.isNoneBlank(comment.getReplyId())) {
            sql1 = "select user_id,comment from ap_comment where id = ?";
            ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, comment.getReplyId());
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()) {
                int userId = resultSet.getInt("user_id");
                replyComment = resultSet.getString("comment");
                //获取用户名称
                sql1 = "select name from ap_user where id = ?";
                ps1 = connection.prepareStatement(sql1);
                ps1.setInt(1, userId);
                ResultSet resultSet1 = ps1.executeQuery();
                if (resultSet1.next()) {
                    name = resultSet1.getString("name");
                }
            }
        }
        //解析用户信息
        LoginVo loginUser = JWTUtils.parseToken(token);
        sql1 = "insert into ap_comment (news_id,user_id,create_time,comment,reply_id,reply_name,reply_comment) values (?,?,?,?,?,?,?)";
        ps1 = connection.prepareStatement(sql1);
        ps1.setInt(1, comment.getNewsId());
        ps1.setInt(2, loginUser.getId());
        ps1.setString(3, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if (StringUtils.isNoneBlank(comment.getReplyId())) {
            ps1.setString(4, comment.getReplyComment());
            ps1.setString(5, comment.getReplyId());
            ps1.setString(6, name);
            ps1.setString(7, replyComment);
        } else {
            ps1.setString(4, comment.getComment());
            ps1.setString(5, "0");
            ps1.setString(6, null);
            ps1.setString(7, null);
        }
        ps1.executeUpdate();
        connection.close();
        return R.ok("评论成功");
    }

    /**
     * 获取评论递归
     *
     * @param newsId
     * @param commentId
     * @return
     * @throws Exception
     */
    @Override
    public R getCommentTree(String newsId, String commentId) throws Exception {
        Connection connection = JDBCUtil.connection();
        //查询所有评论
        String sql1 = "select * from ap_comment INNER JOIN ap_user on ap_comment.user_id = ap_user.id " +
                "where ap_comment.news_id = ? ";
        PreparedStatement ps1 = connection.prepareStatement(sql1);
        ps1.setString(1, newsId);
        ResultSet resultSet = ps1.executeQuery();

        //所有评论数据
        List<CommentVo> allCommentVo = new ArrayList<>();
        while (resultSet.next()) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(resultSet.getInt("id"));
            commentVo.setImage(resultSet.getString("image"));
            commentVo.setName(resultSet.getString("name"));
            commentVo.setComment(resultSet.getString("comment"));
            commentVo.setReplyId(resultSet.getString("reply_id"));
            commentVo.setReplyName(resultSet.getString("reply_name"));
            commentVo.setReplyComment(resultSet.getString("reply_comment"));
            commentVo.setCreateTime(resultSet.getTime("create_time"));
            allCommentVo.add(commentVo);
        }

        //查找出某个评论的子数据
        List<CommentVo> commentList = allCommentVo.stream().filter(item ->
                item.getReplyId().equals(commentId)).collect(Collectors.toList());
        //获取二级及其以下
        List<CommentVo> twoListComment = allCommentVo.stream().filter(item ->
                !item.getReplyId().equals("0")).collect(Collectors.toList());
        //获取所有回复的数据一级
        List<CommentVo> childrenData = getChildrenData(commentList, twoListComment, new ArrayList<>());
        connection.close();

        return R.ok(childrenData);
    }

    /**
     * 递归查询所有数据
     *
     * @param commentList
     * @param allCommentList
     * @return
     */
    private List<CommentVo> getChildrenData(List<CommentVo> commentList, List<CommentVo> allCommentList,
                                            List<CommentVo> voList) {

        for (CommentVo commentVo : commentList) {
            voList.add(commentVo);
            //查找子级数据
            List<CommentVo> childrenList = allCommentList.stream().filter(item ->
                    item.getReplyId().equals(commentVo.getId().toString())).collect(Collectors.toList());
            this.getChildrenData(childrenList, allCommentList, voList);
        }

        return voList;
    }

    @Override
    public R getFirstComment(String newsId) throws Exception {
        Connection connection = JDBCUtil.connection();
        String sql1 = "select * from ap_comment INNER JOIN ap_user on ap_comment.user_id = ap_user.id " +
                "where ap_comment.news_id = ? and reply_id = ? ";
        PreparedStatement ps1 = connection.prepareStatement(sql1);
        PreparedStatement ps2 = null;
        ps1.setString(1, newsId);
        ps1.setString(2, "0");
        ResultSet resultSet = ps1.executeQuery();

        List<CommentVo> commentVos = new ArrayList<>();
        while (resultSet.next()) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(resultSet.getInt("id"));
            commentVo.setImage(resultSet.getString("image"));
            commentVo.setName(resultSet.getString("name"));
            commentVo.setComment(resultSet.getString("comment"));
            commentVo.setReplyComment(resultSet.getString("reply_comment"));
            commentVo.setCreateTime(resultSet.getTime("create_time"));

            //判断是否有回复
            String sql2 = "select * from ap_comment where reply_id = ? ";
            ps2 = connection.prepareStatement(sql2);
            ps2.setString(1, String.valueOf(resultSet.getInt("id")));
            ResultSet resultSet2 = ps2.executeQuery();
            if (resultSet2.next()) {
                commentVo.setChildren(true);
            } else {
                commentVo.setChildren(false);
            }
            commentVos.add(commentVo);

        }
        JDBCUtil.closeConn(ps2, connection);
        JDBCUtil.closeConn(ps1, connection);


        return R.ok(commentVos);
    }
}
